package com.iweb.controller;

import com.iweb.pojo.User;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import java.util.*;

@RestController
@RequestMapping("users")
public class UserController {

    static Map<Integer, User> users = Collections.synchronizedMap(new HashMap<Integer, User>());

//    @ApiOperation(value = "测试", notes = "测试工程是否能够运行")
//    @GetMapping("hello")
//    public String hello(String name) {
//        return String.format("hello %s", name);
//    }

    @ApiOperation(value = "获取用户列表", notes = "获取用户列表")
    @GetMapping()
    public List<User> selectUserList() {
        return new ArrayList<>(users.values());
    }

    @ApiOperation(value = "添加用户", notes = "添加用户")
    @ApiImplicitParam(name = "user", value = "用户详细信息user", required = true, dataTypeClass = User.class)
    @PostMapping
    public String addUser(@RequestBody User user) {
        users.put(user.getId(), user);
        return "success";
    }

    @ApiOperation(value = "查询用户", notes = "根据用户id查询用户")
    @ApiImplicitParam(name = "id", value = "用户id", required = true, dataTypeClass = Integer.class)
    @GetMapping("selectUser/{id}")
    public User selectUser(@PathVariable Integer id) {
        return users.get(id);
    }

    @ApiOperation(value = "修改用户基本信息", notes = "根据用户的id修改用户的基本信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "用户id", required = true, dataTypeClass = Integer.class),
            @ApiImplicitParam(name = "user", value = "需要修改的基本信息", required = true, dataTypeClass = User.class)
    })
    @PutMapping("updateUser/{id}")
    public String updateUser(@PathVariable Integer id, @RequestBody User user) {
        User u = users.get(id);
        BeanUtils.copyProperties(user, u);
        return "success";
    }

    @ApiOperation(value = "删除用户", notes = "根据用户的id删除用户")
    @ApiImplicitParam(name = "id", defaultValue = "0", value = "需要删除的用户id", required = true, dataTypeClass = Integer.class)
    @DeleteMapping("delete/{id}")
    public String deleteUser(@PathVariable Integer id) {
        users.remove(id);
        return "success";
    }

}
